package mt.controller;

import lombok.RequiredArgsConstructor;
import mt.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;


    @GetMapping("/userRegister")
    public String toUserRegister() {
        return "userRegister";
    }

    @GetMapping("/userLogin")
    public String toUserLogin() {
        return "/userLogin";
    }


    @PostMapping("/userRegister")
    public String userRegister(String username, String password,Model model) {
        int result = userService.register(username,password);
        if (result == -1) {
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            model.addAttribute("message","用户名已存在");
            return "/userRegister";
        }
        return "/userLogin";
    }

    @PostMapping("/userLogin")
    public String userLogin(String username, String password, Model model) {

        int result = userService.login(username, password);
        if (result == -1) {
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            model.addAttribute("message","用户名不存在");
            return "/userLogin";
        }
        if (result == 0) {
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            model.addAttribute("message","密码错误");
            return "/userLogin";
        }

        return "redirect:/productList";
    }

}
